// 输入框验证
import { AnyObject } from "@/assets/types/type";
import { AppDispatch, RootState } from "@/store/configureStore";
import mammoth from "mammoth";
import { useSelector } from "react-redux";
import { TypedUseSelectorHook, useDispatch } from "react-redux";
import * as XLSX from "xlsx";

export type ExcelJsonType = Record<string, any>;

export const useVerification = () => {
  function verification(
    setError: (bol: boolean) => void,
    setErrorMessage: (str: string) => void,
    errorMessage: string,
    value: string,
    setValue?: (value: any) => void,
    errorMessage2?: string,
    reg?: RegExp
  ) {
    setValue?.(value);
    if (value == "") {
      setError(true);
      setErrorMessage(errorMessage);
    } else {
      setError(false);
      setErrorMessage("");
    }
    if (reg) {
      if (!reg.test(value)) {
        setError(true);
        setErrorMessage(errorMessage2 as string);
      } else {
        setError(false);
        setErrorMessage("");
      }
    }
  }
  return { verification };
};

// 模糊查询
export const useFilterArray = () => {
  function filterArray<T extends AnyObject>(
    e: string,
    filterArray: T[],
    setFilteredAarray: (value: T[]) => void
  ) {
    let filteredArray = filterArray.filter((value) => {
      return Object.entries(value).some(([key, value]) => {
        if (typeof value === "string") {
          return value.includes(e);
        }
        return !key;
      });
    });
    setFilteredAarray(filteredArray);
  }
  return { filterArray };
};

export const useFormatNumber = () => {
  function formatNumber(payload: number, fixed: number) {
    if (typeof payload !== "number") {
      throw new Error("input must be a number");
    }

    if (payload <= 10000) {
      return payload.toString();
    }
    const formattedValue = payload / 10000;
    return formattedValue.toFixed(fixed).replace(/\.0$/, "") + "万";
  }
  return { formatNumber };
};

export const useExportExecl = () => {
  function exportExecl(data: any, execlName: string) {
    console.log(1111);

    if (!data) return;
    const worksSheet = XLSX.utils.json_to_sheet(data); // 将json数据转换为工作表
    const workbook = XLSX.utils.book_new(); // 创建新工作簿
    XLSX.utils.book_append_sheet(workbook, worksSheet, "Sheet1");

    // 导出为 Execl 文件
    XLSX.writeFile(workbook, execlName);
  }

  return exportExecl;
};

export const useExeclToJson = () => {
  function execlToJson(
    e: React.ChangeEvent<HTMLInputElement>,
    setJsonData: (value: ExcelJsonType | ExcelJsonType[]) => void
  ) {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => {
      const data = new Uint8Array(e.target?.result as ArrayBuffer);

      const workbook = XLSX.read(data, { type: "array" });

      // 转换为json
      const sheetName = workbook.SheetNames[0];
      const worksSheet = workbook.Sheets[sheetName];
      const json = XLSX.utils.sheet_to_json(
        worksSheet as ExcelJsonType | ExcelJsonType[]
      );
      let data1 = json.map((item: any) => {
        return {
          acc: item["邮箱账号"],
          pwd: item["密码"],
          recover: item["辅助邮箱"],
          name: item["用户名"] ? item["用户名"] : "",
        };
      });
      setJsonData(data1);
    };
    reader.readAsArrayBuffer(file);
  }
  return execlToJson;
};

export const useTextReader = () => {
  async function textReader(
    e: React.ChangeEvent<HTMLInputElement>,
    setText: (value: string[]) => void
  ) {
    const file = e.target.files?.[0];
    if (!file) return;

    const extension = file.name.split(".").pop()?.toLocaleLowerCase();
    if (extension === "docx") {
      const reader = new FileReader();
      reader.onload = async (e) => {
        const arrayBuffer = e.target?.result as ArrayBuffer;
        const result = await mammoth.extractRawText({ arrayBuffer });
        const text = result.value;
        const lines = text.split(/\r?\n/);

        // 二次筛选 防止数组数据有空值
        const filteredArray = lines.filter(
          (item) => item !== "" && item !== " "
        );
        setText(filteredArray);
      };
      reader.readAsArrayBuffer(file);
    } else if (extension === "txt") {
      const reader = new FileReader();
      reader.onload = (e) => {
        const text = e.target?.result as string;
        const lines = text.split(/\r?\n/);
        setText(lines);

        // 二次筛选 防止数组数据有空值
        const filteredArray = lines.filter((item) => item !== "");
        setText(filteredArray);
      };
      reader.readAsText(file);
    } else {
      console.warn("Unsupported file type");
    }
  }

  return textReader;
};

export const useAppDispatch: () => AppDispatch = useDispatch;

export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
